// pages/test/index.ts
import { travelApi } from '../../utils/api';

Page({
  data: {
    testResult: '',
    loading: false,
  },

  onLoad() {
    this.runTest();
  },

  async runTest() {
    this.setData({ loading: true, testResult: '开始测试...\n' });

    try {
      // 测试API连接
      this.appendResult('测试API连接...');
      const testRecord = await travelApi.getDetail(26); // 使用之前创建的测试记录ID
      
      this.appendResult('✅ API连接成功');
      this.appendResult(`记录标题: ${testRecord.title}`);
      this.appendResult(`开始日期: ${testRecord.start_date} (类型: ${typeof testRecord.start_date})`);
      this.appendResult(`结束日期: ${testRecord.end_date} (类型: ${typeof testRecord.end_date})`);
      
      // 测试日期格式化
      this.appendResult('\n测试日期格式化...');
      const formattedStart = this.formatDate(testRecord.start_date);
      const formattedEnd = this.formatDate(testRecord.end_date);
      
      this.appendResult(`格式化开始日期: ${formattedStart}`);
      this.appendResult(`格式化结束日期: ${formattedEnd}`);
      
      // 测试数据完整性
      this.appendResult('\n测试数据完整性...');
      this.appendResult(`记录对象: ${JSON.stringify(testRecord, null, 2)}`);

    } catch (error: any) {
      this.appendResult(`❌ 测试失败: ${error.message || error}`);
      console.error('测试错误:', error);
    } finally {
      this.setData({ loading: false });
    }
  },

  formatDate(dateString: string): string {
    if (!dateString) {
      return '未设置日期';
    }
    
    try {
      const date = new Date(dateString);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '无效日期';
      }
      
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch (error) {
      console.error('日期格式化错误:', error);
      return '日期格式错误';
    }
  },

  appendResult(text: string) {
    this.setData({
      testResult: this.data.testResult + text + '\n'
    });
  },

  onCopyResult() {
    wx.setClipboardData({
      data: this.data.testResult,
      success: () => {
        wx.showToast({
          title: '结果已复制',
          icon: 'success'
        });
      }
    });
  }
});
